package com.xzq.wanandroid.base.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.xzq.wanandroid.base.presenter.BasePresenter;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.blankj.utilcode.util.CrashUtils.init;

public abstract class BaseFragment<V, P extends BasePresenter<V>> extends Fragment {
    /**
     * 封装toast对象
     */
    private Toast toast;
    private View mRootView;
    private P mPresenter;
    private Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载布局文件
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
        }
        mPresenter = createPresenter();
        unbinder = ButterKnife.bind(this, mRootView);

        if (mPresenter != null) {
            mPresenter.attchView((V) this);
        }
        initView();
        return mRootView;
    }

    /**
     * 初始化View
     */
    protected abstract void initView();

    protected abstract P createPresenter();

    /**
     * 初始化布局的文件ID
     */
    protected abstract int getLayoutId();


    /**
     * 保证同一按钮在1秒内只响应一次点击事件
     */
    public abstract class OnSingleClickListener implements View.OnClickListener {

        //两次点击按钮的最小间隔，目前为1000
        private static final int Min_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        public abstract void onSingleClick(View view);

        @Override
        public void onClick(View v) {
            long currentTimeMillis = System.currentTimeMillis();
            lastClickTime = currentTimeMillis;
            if (currentTimeMillis - lastClickTime >= Min_CLICK_DELAY_TIME) {
                onSingleClick(v);
            }
        }

    }

    /**
     * 同一按钮在短时间内可重复响应点击事件
     */
    public abstract class OnMultiClickListener implements View.OnClickListener {

        public abstract void onMultiClick(View view);

        @Override
        public void onClick(View v) {
            onMultiClick(v);
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (mPresenter != null) {
            mPresenter.detechView();
        }
    }
}
